package com.dianrui.operation.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;

import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.dianrui.operation.Constant;
import com.dianrui.operation.R;

import com.dianrui.operation.bean.BikePointModel;
import com.dianrui.operation.okhttp.XHttpRequest;
import com.dianrui.operation.util.SharedUtil;
import com.dianrui.operation.util.StringUtils;

import com.dianrui.operation.util.ToastUtil;
import com.dianrui.operation.util.Url;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ShowLocationActivity extends BaseActivity implements AMapLocationListener {
    private AMap aMap;
    private List<BikePointModel> bikePointList = new ArrayList<>();
    private List<LatLng> points = new ArrayList<>();
    private List<LatLng> fixpoints = new ArrayList<>();
    //声明mlocationClient对象
    public AMapLocationClient mLocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private boolean isFirstLoc = true;
    private BitmapDescriptor bitD_NoStop;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.mapviews)
    MapView mapviews;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapviews.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapviews.onSaveInstanceState(outState);
    }


    @Override
    public int getContentViewId() {
        return R.layout.show_location;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapviews.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapviews.onPause();
    }

    @Override
    public void initView() {
        title.setText("查看定位");
        if (aMap == null) {
            aMap = mapviews.getMap();
        }
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);

        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(ShowLocationActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(ShowLocationActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            }
        } else {
            startLocation();
        }
        network();
        View view1 = LayoutInflater.from(ShowLocationActivity.this).inflate(R.layout.over_nostop_point, null);
        bitD_NoStop=BitmapDescriptorFactory.fromView(view1);
    }

    @Override
    public void initData() {}

    //开始定位
    private void startLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为Hight_Accuracy高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }

    private void network() {
        JsonObject networksJsonobject = new JsonObject();
        networksJsonobject.addProperty("admin_id", spUtils.getString("admin_id"));
        XHttpRequest.getInstance().postRequests(SharedUtil.getUrl() + Url.GETNETWORK_BIKE, networksJsonobject.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                if (null != bikePointList && bikePointList.size() > 0) {
                                    bikePointList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        BikePointModel bikeModel = new BikePointModel();
                                        bikeModel.blat = jsonArray.optJSONObject(i).optDouble("blat");
                                        bikeModel.blng = jsonArray.optJSONObject(i).optDouble("blng");
                                        bikeModel.vehicle_number = jsonArray.optJSONObject(i).optString("vehicle_number");
                                        bikePointList.add(bikeModel);
                                        LayoutInflater inflater = LayoutInflater.from(ShowLocationActivity.this);
                                        View view = inflater.inflate(R.layout.over_bike_point, null);
                                        TextView markernum = view.findViewById(R.id.locnum_blue);
                                        int number = Integer.parseInt(bikePointList.get(i).vehicle_number);
                                        if (number > 9) {
                                            String showMarkernumplus = 9 + "+" + "";
                                            markernum.setText(showMarkernumplus);
                                        } else {
                                            String showVehicleNumber = bikePointList.get(i).vehicle_number + "";
                                            markernum.setText(showVehicleNumber);
                                        }
                                        Marker marker = aMap.addMarker(new MarkerOptions()
                                                .position(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng))
                                                .icon(BitmapDescriptorFactory.fromView(view)));
                                        if ("1".equals(jsonArray.optJSONObject(i).optString("fixed_type"))) {
                                            points.clear();
                                            JSONArray jsonArray3 = jsonArray.optJSONObject(i).optJSONArray("fixed_path");
                                            if (jsonArray3.length() > 0) {
                                                for (int j = 0; j <= jsonArray3.length(); j++) {
                                                    if (j == jsonArray3.length()) {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(0);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    } else {
                                                        JSONObject jsonObject1 = jsonArray3.optJSONObject(j);
                                                        points.add(new LatLng(jsonObject1.optDouble("lat"), jsonObject1.optDouble("lng")));
                                                    }

                                                }

                                                if (points.size() < 2) {
                                                    return;
                                                }

                                                if (jsonArray.optJSONObject(i).optString("is_forbid").equals("1")) {
                                                    aMap.addPolyline((new PolylineOptions()).addAll(points)
                                                            .width(4).setDottedLine(true).color(Color.RED));
                                                    MarkerOptions markerOptions1 = new MarkerOptions();
                                                    markerOptions1.position(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng)).icon(bitD_NoStop);
                                                    Marker marker1 = aMap.addMarker(markerOptions1);


                                                }else {
                                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                                    List<Integer> textureIndexs = new ArrayList<>();
                                                    textureIndexs.add(i);
                                                    List<LatLng> overLatlngList = new ArrayList<>(points);

                                                    PolylineOptions polylineOptions = new PolylineOptions();
                                                    polylineOptions.addAll(overLatlngList);
                                                    polylineOptions.width(4);
                                                    polylineOptions.setCustomTextureList(textureList);
                                                    polylineOptions.setCustomTextureIndex(textureIndexs);
                                                    polylineOptions.setDottedLine(true);
                                                    polylineOptions.setUseTexture(true);
                                                    aMap.addPolyline(polylineOptions);
                                                }
                                            }
                                        }else {
                                            int networkRange = jsonArray.optJSONObject(i).optInt("network_range");
                                            aMap.addCircle(new CircleOptions()
                                                    .center(new LatLng(bikePointList.get(i).blat, bikePointList.get(i).blng))
                                                    .radius(networkRange)
                                                    .fillColor(Color.argb(46,64,194,134)).strokeWidth(4).strokeColor(Color.argb(46,64,194,134)));
                                        }
                                    }
                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startLocation();
                }
                break;

            default:
                break;

        }

    }

    @OnClick({R.id.back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;

            default:
                break;

        }
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            if (isFirstLoc) {
                aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                isFirstLoc = false;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapviews.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        if (bitD_NoStop != null) {
            bitD_NoStop.recycle();
            bitD_NoStop=null;
        }

    }
}
